package com.deer.wms.base.system.web.box;

import com.deer.wms.base.system.finalUtil.AreaInfoId;
import com.deer.wms.base.system.finalUtil.BoxInfoState;
import com.deer.wms.base.system.finalUtil.CellInfoState;
import com.deer.wms.base.system.model.TaskTypeConstant;
import com.deer.wms.base.system.model.bill.*;
import com.deer.wms.base.system.model.box.*;
import com.deer.wms.base.system.model.check.BoxItemCheck;
import com.deer.wms.base.system.model.check.BoxItemCheckDetail;
import com.deer.wms.base.system.model.fpStor.FpMoveMaster;
import com.deer.wms.base.system.model.item.ItemInfo;
import com.deer.wms.base.system.model.task.RequestMove;
import com.deer.wms.base.system.model.task.RequestWcsRedis;
import com.deer.wms.base.system.model.task.TaskInfo;
import com.deer.wms.base.system.model.task.TaskInfoDto;
import com.deer.wms.base.system.model.ware.CellInfo;
import com.deer.wms.base.system.model.ware.CellInfoDto;
import com.deer.wms.base.system.model.zh.ShelfPlan;
import com.deer.wms.base.system.model.zh.WorkTasks;
import com.deer.wms.base.system.service.ServerVisitAddressService;
import com.deer.wms.base.system.service.SubInventoryService;
import com.deer.wms.base.system.service.SubinventoryTransferRecordService;
import com.deer.wms.base.system.service.bill.BillOutSapService;
import com.deer.wms.base.system.service.bill.IBillOutMasterService;
import com.deer.wms.base.system.service.box.BoxInfoService;
import com.deer.wms.base.system.service.box.BoxItemErrorService;
import com.deer.wms.base.system.service.box.IBoxItemService;
import com.deer.wms.base.system.service.fpStor.FpMoveService;
import com.deer.wms.base.system.service.item.IItemInfoService;
import com.deer.wms.base.system.service.task.ITaskInfoService;
import com.deer.wms.base.system.service.ware.ICellInfoService;
import com.deer.wms.base.system.service.zh.ShelfPlanService;
import com.deer.wms.base.system.service.zh.WorkTasksService;
import com.deer.wms.base.system.util.DateUtil;
import com.deer.wms.base.system.util.JedisServiceUtil;
import com.deer.wms.common.annotation.Log;
import com.deer.wms.common.core.controller.BaseController;
import com.deer.wms.common.core.domain.AjaxResult;
import com.deer.wms.common.core.page.TableDataInfo;
import com.deer.wms.common.core.result.CommonCode;
import com.deer.wms.common.core.result.Result;
import com.deer.wms.common.core.result.ResultGenerator;
import com.deer.wms.common.core.text.Convert;
import com.deer.wms.common.enums.BusinessType;
import com.deer.wms.common.exception.ServiceException;
import com.deer.wms.common.utils.DateUtils;
import com.deer.wms.common.utils.GuidUtils;
import com.deer.wms.common.utils.poi.ExcelUtil;
import com.deer.wms.framework.util.MyUtils;
import com.deer.wms.framework.util.ShiroUtils;
import com.deer.wms.system.domain.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 组盘 信息操作处理
 *
 * @author guo
 * @date 2019-06-03
 */
@Controller
@RequestMapping("/in/boxItem")
@Slf4j
public class BoxItemController extends BaseController
{
    private String prefix = "in/boxItem";
	@Autowired
	private ShelfPlanService shelfPlanService;
	@Autowired
	private IBoxItemService boxItemService;
	@Autowired
	private SubinventoryTransferRecordService subinventoryTransferRecordService;
	@Autowired
	private ServerVisitAddressService serverVisitAddressService;
	@Autowired
	private BoxInfoService boxInfoService;
	@Autowired
	private ITaskInfoService taskInfoService;
	@Autowired
	private ICellInfoService cellInfoService;
	@Autowired
	private IItemInfoService itemInfoService;
	@Autowired
	private SubInventoryService subInventoryService;
	@Autowired
	private BoxItemErrorService boxItemErrorService;
	@Autowired //redis工具
	private JedisServiceUtil jedisServiceUtil;
	@Autowired //工作任务
	private WorkTasksService workTasksService;
	@Autowired //移库
	private FpMoveService fpMoveService;
	@Autowired //出库单
	private IBillOutMasterService billOutMasterService;
	@Autowired //SAP出库
	private BillOutSapService billOutSapService;

	//@RequiresPermissions("in:boxItem:view")
	@GetMapping("/page")
	public String boxItem()
	{
	    return prefix + "/boxItem";
	}

	//@RequiresPermissions("in:inventoryManage:view")
	@GetMapping("/inventoryManagePage")
	public String inventoryManage(Model model)
	{
		List<String> name = itemInfoService.findName();
		model.addAttribute("itemName",name);
		return prefix + "/inventoryManagement";
	}

	/**
	 * 暂存区页面跳转
	 * @author 申紫微
	 * @date 14:56 2021/6/19
	 * @params
	 * @return  java.lang.String
	 **/
	//@RequiresPermissions("in:bufferStorage:view")
	@GetMapping("/bufferStorage")
	public String bufferStorage(){
		return prefix + "/bufferStorage";
	}


	@GetMapping("/bufferStorageDetail")
	public String bufferStorageDetail(){
		return prefix + "/bufferStorageDetail";
	}



	/**
	 *查询区库存
	 * @author 李帅辰
	 * @date 2021/6/25 19:51
	 * @return com.deer.wms.common.core.page.TableDataInfo
	 */
	@PostMapping("/bufferStorageFindList")
	@ResponseBody
	public TableDataInfo bufferStorageFindList(BoxItemCriteria boxItemCriteria) {
		startPage();
		boxItemCriteria.setAreaId(AreaInfoId.AREAINFO_TEMPORARY_AREA);
		List<BoxItemExport> list = boxItemService.findBoxItemDtoMainListByAreaId(boxItemCriteria);
		return getDataTable(list);
	}
	/*@PostMapping("/export")
	@ResponseBody
	public AjaxResult export(BoxItemCriteria boxItemCriteria) {

		List<BoxItemDto> list = boxItemService.findBoxItemDtoListByAreaId(boxItemCriteria);
		ExcelUtil<BoxItemDto> util = new ExcelUtil<BoxItemDto>(BoxItemDto.class);
		return util.exportExcel(list, "异常区");
	}
	*//**
	 * 导出列表
	 *//*
	//@RequiresPermissions("in:billInMaster:partExcel")
	@PostMapping("/partExcel")
	@ResponseBody
	public AjaxResult partExcel(@RequestParam String ids) {
		List<BoxItemDto> byIds=new ArrayList();
		String[] split = ids.split(",");
		for (String s:split
		) {
			BoxItemCriteria  b=new BoxItemCriteria ();
			b.setAreaId(Integer.parseInt(s));
			List<BoxItemDto> list = boxItemService.findBoxItemDtoListByAreaId(b);
			for (BoxItemDto bs:list
			) {
				byIds.add(bs);
			}

		}
		// List<BillInSapDto> billInSapList = billInSapService.findBillInSapDtoList(billInSapCriteria);
		ExcelUtil<BoxItemDto> util = new ExcelUtil<BoxItemDto>(BoxItemDto.class);
		return util.exportExcel(byIds, "异常区");
	}*/




	@PostMapping("/bufferStorageDetailList")
	@ResponseBody
	public TableDataInfo bufferStorageDetailList(BoxItemCriteria boxItemCriteria) {
		startPage();
		boxItemCriteria.setAreaId(AreaInfoId.AREAINFO_TEMPORARY_AREA);
		List<BoxItemDto> list = boxItemService.findBoxItemDtoDetailByAreaId(boxItemCriteria);
		return getDataTable(list);
	}


	/**
	 * 缓存线区页面跳转
	 * @author 申紫微
	 * @date 14:57 2021/6/19
	 * @params
	 * @return java.lang.String
	 **/
	//@RequiresPermissions("in:cacheStorge:view")
	@GetMapping("/cacheStorage")
	public String cacheStorge(){
		return prefix + "/cacheStorge";
	}


	/**
	 *查询缓存线区库存
	 * @author 李帅辰
	 * @date 2021/6/25 19:51
	 * @return com.deer.wms.common.core.page.TableDataInfo
	 */
	@PostMapping("/cacheStorgeFindList")
	@ResponseBody
	public TableDataInfo cacheStorgeFindList(BoxItemCriteria boxItemCriteria) {
		startPage();
		boxItemCriteria.setAreaId(AreaInfoId.AREAINFO_CACHE_LINE);
		List<BoxItemDto> list = boxItemService.findBoxItemDtoListByAreaId(boxItemCriteria);
		return getDataTable(list);
	}

	//@RequiresPermissions("in:boxItem:exportCacheStorge")
	@PostMapping("/exportCacheStorge")
	@ResponseBody
	public AjaxResult exportCacheStorge(BoxItemCriteria boxItemCriteria)
	{
		boxItemCriteria.setAreaId(AreaInfoId.AREAINFO_CACHE_LINE);
		List<BoxItemDto> list = boxItemService.findBoxItemDtoListByAreaId(boxItemCriteria);
		ExcelUtil<BoxItemDto> util = new ExcelUtil<BoxItemDto>(BoxItemDto.class);
		return util.exportExcel(list, "库存");
	}


	/**
	 * 库存总览页面跳转
	 * @author 李帅辰
	 * @date 2021/6/27 13:43
	 * @params
	 * @return java.lang.String
	 **/
	//@RequiresPermissions("in:boxPandectPage:view")
	@GetMapping("/boxPandectPage")
	public String boxPandectPage(){
		return prefix + "/boxPandectPage";
	}



	/*日结库存报表*/
	@PostMapping("/boxPandect")
	@ResponseBody
	public TableDataInfo boxPandect(BoxItemToday boxItemToday) {
		startPage();
		Date now = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		String today = sf.format(now);
		List<BoxItemToday> list;

		if(boxItemToday.getStartTime()==null || !boxItemToday.getStartTime().equals(today)){
			//不是今天,查保存记录
			list  = boxItemService.selectBoxItemHistory(boxItemToday);
		}else {
			//是今天,实时查询
			list = boxItemService.selectBoxItemToday(boxItemToday);
		}
		return getDataTable(list);
	}

	//@RequiresPermissions("in:boxItem:exportBoxPandect")
	@PostMapping("/exportBoxPandect")
	@ResponseBody
	public AjaxResult exportBoxPandect(BoxItemToday boxItemToday)
	{
		List<BoxItemToday> list = boxItemService.selectBoxItemToday(boxItemToday);
		ExcelUtil<BoxItemToday> util = new ExcelUtil<BoxItemToday>(BoxItemToday.class);
		return util.exportExcel(list, "当日库存");
	}


	/**
	 * 周转区页面跳转
	 * @author 申紫微
	 * @date 15:00 2021/6/19
	 * @params
	 * @return java.lang.String
	 **/
	//@RequiresPermissions("in:revolutionStorage:view")
	@GetMapping("/revolutionStorage")
	public String revolutionStorage(){
		return prefix + "/revolutionStorage";
	}


	/**
	 * 周转区库存查询
	 * @author 李帅辰
	 * @date 2021/6/25 20:03
	 * @return com.deer.wms.common.core.page.TableDataInfo
	 */
	@PostMapping("/revolutionStorageList")
	@ResponseBody
	public TableDataInfo revolutionStorageList(BoxItemCriteria boxItemCriteria){
		startPage();
		boxItemCriteria.setAreaId(AreaInfoId.AREAINFO_TURNOVER);
		List<BoxItemDto> boxItemDtoList = boxItemService.selectRevolutionStorageList(boxItemCriteria);
		return getDataTable(boxItemDtoList);
	}

	/**
	 * 根据货区查询整托信息(周转区、暂存区)
	 * @author 申紫微
	 * @date 11:15 2021/7/5
	 * @params boxItemCriteria
	 * @return com.deer.wms.common.core.page.TableDataInfo
	 **/
	@PostMapping("/selectWholeTorrInfo")
	@ResponseBody
	public TableDataInfo bufferStorageFindListV2(BoxItemCriteria boxItemCriteria){
		startPage();
		List<BoxItemDto> boxItemDtoList = boxItemService.selectRevolutionStorageList(boxItemCriteria);
		return getDataTable(boxItemDtoList);
	}

	//@RequiresPermissions("in:boxItem:exportRevolutionStorage")
	@PostMapping("/export")
	@ResponseBody
	public AjaxResult exportRevolutionStorage(BoxItemCriteria boxItemCriteria)
	{
		boxItemCriteria.setAreaId(AreaInfoId.AREAINFO_TURNOVER);
		List<BoxItemDto> boxItemDtoList = boxItemService.selectRevolutionStorageList(boxItemCriteria);
		ExcelUtil<BoxItemDto> util = new ExcelUtil<BoxItemDto>(BoxItemDto.class);
		return util.exportExcel(boxItemDtoList, "缓存区状态");
	}
	//carrierId
	/**
	 * 导出列表
	 */
	//@RequiresPermissions("in:billInMaster:partExcel")
	@PostMapping("/partExcelCacheStorge")
	@ResponseBody
	public AjaxResult partExcel(@RequestParam  String ids) {
		List<BoxItemDto> byIds=new ArrayList();
		String[] split = ids.split(",");
		for (String s:split
		) {
			BoxItemCriteria b=new BoxItemCriteria ();
			b.setCarrierId(s);
			List<BoxItemDto> boxItemDtoList = boxItemService.selectRevolutionStorageList(b);
			for (BoxItemDto bs:boxItemDtoList
			) {
				byIds.add(bs);
			}

		}
		// List<BillInSapDto> billInSapList = billInSapService.findBillInSapDtoList(billInSapCriteria);
		ExcelUtil<BoxItemDto> util = new ExcelUtil<BoxItemDto>(BoxItemDto.class);
		return util.exportExcel(byIds, "缓存区状态");
	}


	/**
	 * 跳转周转区库存明细
	 * @author 李帅辰
	 * @date 2021/6/25 20:05
	 * @return java.lang.String
	 */
	@GetMapping("/revolutionStorageDetail")
	public String revolutionStorageDetail(){
		return prefix + "/revolutionStorageDetail";
	}

	/**
	 *chaxun 周转区库存明细
	 * @author 李帅辰
	 * @date 2021/6/25 20:05
	 * @return com.deer.wms.common.core.page.TableDataInfo
	 */
	@PostMapping("/revolutionStorageDetailList")
	@ResponseBody
	public TableDataInfo revolutionStorageDetailList(BoxItemCriteria boxItemCriteria) {
		startPage();
		boxItemCriteria.setAreaId(AreaInfoId.AREAINFO_TURNOVER);
		List<BoxItemDto> list = boxItemService.findBoxItemDtoListByAreaId(boxItemCriteria);
		return getDataTable(list);
	}

	/*质量转换单列表*/
	@PostMapping("/findList")
	@ResponseBody
	public TableDataInfo findList(BoxItemStateDetail boxItemStateDetail) {
		startPage();
		List<BoxItemStateDetail> list = boxItemService.selectBoxItemStateList(boxItemStateDetail);
		return getDataTable(list);
	}



	/*物料转换*/
	@PostMapping("/findStateById")
	@ResponseBody
	public BoxItemState findStateById(@RequestParam Integer stateId) {
		return boxItemService.findStateById(stateId);
	}
	/*批次转换列表*/
	@PostMapping("/findBoxItemBatchList")
	@ResponseBody
	public TableDataInfo findBoxItemBatchList(BoxItemBatchDetail boxItemBatchDetail) {
		startPage();
		List<BoxItemBatchDetail> list = boxItemService.selectBoxItemBatchList(boxItemBatchDetail);
		return getDataTable(list);
	}
	/*物料转换明细*/
	@PostMapping("/findListdetailById")
	@ResponseBody
	public TableDataInfo findListdetailById(@RequestParam Integer stateId) {
		startPage();
		List<BoxItemStateDetail> select = boxItemService.findListdetail(stateId);
		return getDataTable(select);
	}
	/*批次转换明细导出*/
	@PostMapping("/partExcelBatch")
	@ResponseBody
	@Transactional
	public AjaxResult partExcelBatch(@RequestParam  String ids) {
		List<BoxItemBatchDetail> byIds = new ArrayList();
		String[] split = ids.split(",");
		int id = 0;
		for (String s:split) {
			id = Integer.parseInt(s);
			BoxItemBatchDetail boxItemBatchDetail = boxItemService.selectBoxItemBatch(id);
			byIds.add(boxItemBatchDetail);
			boxItemService.updateExcelBatchState(id);
		}
		ExcelUtil<BoxItemBatchDetail> util = new ExcelUtil<>(BoxItemBatchDetail.class);
		return util.exportExcel(byIds, "批次转换明细单");
	}
	/*物料转换明细导出*/
	@PostMapping("/partExcelState")
	@ResponseBody
	@Transactional
	public AjaxResult partExcelState(@RequestParam  String ids) {
		List<BoxItemStateDetail> byIds = new ArrayList();
		String[] split = ids.split(",");
		int id = 0;
		for (String s:split) {
			id = Integer.parseInt(s);
			BoxItemStateDetail boxItemStateDetail = boxItemService.selectBoxItemState(id);
			byIds.add(boxItemStateDetail);
			boxItemService.updateExcelStateState(id);
		}
		ExcelUtil<BoxItemStateDetail> util = new ExcelUtil<>(BoxItemStateDetail.class);
		return util.exportExcel(byIds, "批次转换明细单");
	}

	/**
	 * 查询组盘列表
	 */
	//@RequiresPermissions("in:boxItem:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(BoxItem boxItem) {
		startPage();
        List<BoxItem> list = boxItemService.selectBoxItemList(boxItem);
		return getDataTable(list);
	}



	/**
	 * 新建出库单时，选择缓存线对应的库存
	 */
	@PostMapping("/boxList")
	@ResponseBody
	public TableDataInfo boxList(ShelfPlan shelfPlan) {
		startPage();
		List<BoxItemDto> boxItemDtoList = new ArrayList<>();
		List<ShelfPlan> list = shelfPlanService.findShelfPlanList(shelfPlan);
		for (ShelfPlan plan : list) {
			//List<BoxItemDto> quantityByShelfId = boxItemService.getQuantityByShelfId(plan.getShelfId());
			BoxItemCriteria boxItemCriteria = new BoxItemCriteria();
			boxItemCriteria.setShelfId(plan.getShelfId());
			boxItemCriteria.setAreaId(AreaInfoId.AREAINFO_CACHE_LINE);
			List<BoxItemDto> boxItemDtoList1 = boxItemService.boxPandect(boxItemCriteria);
			boxItemDtoList.addAll(boxItemDtoList1);
		}
		return getDataTable(boxItemDtoList);
	}



	/**
	 * 新增组盘
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/boxItemAdd";
	}

	/**
	 * 新增保存组盘
	 */
	//@RequiresPermissions("in:boxItem:add")
	@Log(title = "组盘", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	@Transactional(rollbackFor=Exception.class)
	public Result addSave(BoxItemDto boxItemDto){
		String boxCode = boxItemDto.getBoxCode();
		//String cellCode = boxItemDto.getCellCode();
		//CellInfo cellInfo = cellInfoService.selectCellInfoByCellCode(cellCode);//以修改后的货位编码来查询修改后的货位的详细信息
		//Integer cellId = cellInfo.getCellId();
		BoxInfo boxInfo = new BoxInfo();
		CellInfo cellInfoNow=new CellInfo();
        //String itemCode = boxItemDto.getItemCode();
        //ItemInfo byItemCode = itemInfoService.findByItemCode(itemCode);
        //Integer itemId = byItemCode.getItemId();
        BoxItemDto boxItemDto1 = boxItemService.selectBoxItemByBoxCode(boxCode);
		if(null!=boxItemDto1){
			return ResultGenerator.genFailResult(CommonCode.BXOINFO_ERROR, "false");
		}
//		if(cellInfo.getState()==1||cellInfo.getState()==8){
//			return ResultGenerator.genFailResult(CommonCode.CELLINFO_ERROR, "false");
//		}

		BoxInfoDto boxInfoDto = boxInfoService.getCellIdByBoxCode(boxCode);
		if(null==boxInfoDto){
			boxInfo.setBoxCode(boxCode);
			boxInfo.setBoxState(BoxInfoState.BOXINFO_STATE_ONT);
			boxInfo.setHasGoods(BoxInfoState.BOXINFO_GOODS_ONT);
			//boxInfo.setBoxCellId(cellId);
			boxInfo.setBoxType(2);
			boxInfoService.saveOrUpdate(boxInfo);
			cellInfoNow.setState(CellInfoState.STATE_ONT);
			//cellInfoNow.setCellId(cellId);
            //cellInfoNow.setItemId(itemId);
			cellInfoService.updateCellInfo(cellInfoNow);
		}else {
			Integer boxCellId = boxInfoDto.getBoxCellId();
			if(boxCellId!=0){
				return ResultGenerator.genFailResult(CommonCode.BXOINFO_ERROR, "false");
			}
				cellInfoNow.setState(CellInfoState.STATE_ONT);
				//cellInfoNow.setCellId(cellId);
                //cellInfoNow.setItemId(itemId);
				cellInfoService.updateCellInfo(cellInfoNow);
				//boxInfo.setBoxCellId(cellId);
				boxInfo.setBoxState(BoxInfoState.BOXINFO_STATE_ONT);
				boxInfo.setHasGoods(BoxInfoState.BOXINFO_GOODS_ONT);
				boxInfo.setBoxType(2);
				boxInfo.setBoxCode(boxCode);
				boxInfoService.updateBoxInfo(boxInfo);
		}
		//ItemInfo itemInfo = itemInfoService.findByItemCode(boxItemDto.getItemCode());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date time = null;
//		try {
//			//String pd = boxItemDto.getPd();
//			Date parse = sdf.parse(pd);
//			Integer dateWarning = itemInfo.getDateWarning();
//			time = DateUtil.timeAddByDays(parse, dateWarning);
//		} catch (Exception e) {
//			e.printStackTrace();
//			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//		}
		String expTime = sdf.format(time);
		//boxItemDto.setExp(expTime);//计算预计的过期时间ss
		boxItemDto.setState(0);
		boxItemDto.setWareId(1220);
		int i = boxItemService.insertBoxItem(boxItemDto);
		if(i==0){
			try {
				log.error("新增出库单出错");
				throw new Exception("新增出库单出错，手动抛异常");
			} catch (Exception e) {
				e.printStackTrace();
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
			return ResultGenerator.genFailResult(CommonCode.SERVICE_ERROR, "false");
		}
		return ResultGenerator.genSuccessResult();
	}

	/**
	 * 修改组盘
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
		BoxItemDto boxItem = boxItemService.selectBoxItemById(id);
		//ItemInfo itemInfo = itemInfoService.findByItemCode(boxItem.getItemCode());
		mmap.put("boxItem", boxItem);
//		if(!Objects.isNull(itemInfo)){
//			mmap.put("itemName", itemInfo.getItemName());
//		}
	    return prefix + "/boxItemEdit";
	}

	/**
	 * 修改保存组盘
	 */
	//@RequiresPermissions("in:boxItem:edit")
	@Log(title = "组盘", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Result editSave(BoxItemDto boxItemDto){
       //String  itemCode = boxItemDto.getItemCode();
        //ItemInfo byItemCode = itemInfoService.findByItemCode(itemCode);
        //Integer itemId = byItemCode.getItemId();

		Long id = boxItemDto.getId();//该库存的ID
		BoxItemDto selectBoxItemById = boxItemService.selectBoxItemById(Integer.parseInt(id.toString()));//查询库存的详细信息
		String boxCodeNow = selectBoxItemById.getBoxCode();//修改前的托盘条码
		BoxInfoDto boxInfoDto = boxInfoService.getCellIdByBoxCode(boxCodeNow);
		Integer boxCellId = boxInfoDto.getBoxCellId();//修改前的货位ID
		//String cellCode = boxItemDto.getCellCode();//修改后的货位编码
		String boxCodeEdit = boxItemDto.getBoxCode();//页面修改后的托盘条码
		//CellInfo cellInfoByCellCode = cellInfoService.selectCellInfoByCellCode(cellCode);//以修改后的货位编码来查询修改后的货位的详细信息
		//Integer cellId = cellInfoByCellCode.getCellId();//页面修改后的货位ID
		//判断有无修改货位及托盘
//			if(!(boxCodeNow.equals(boxCodeEdit))||!(cellId.equals(boxCellId))){
//				BoxInfo boxInfoByBoxCode = boxInfoService.getBoxInfoByBoxCode(boxCodeEdit);//判断此时有无此页面修改后的托盘条码
//					if(null==boxInfoByBoxCode){
//						//如果没有，则添加到box_info
//						//新增现在的
//						BoxInfo boxInfo = new BoxInfo();
//						boxInfo.setBoxCode(boxCodeEdit);
//						boxInfo.setBoxState(BoxInfoState.BOXINFO_STATE_ONT);
//						boxInfo.setHasGoods(BoxInfoState.BOXINFO_GOODS_ONT);
//						boxInfo.setBoxCellId(cellId);
//						boolean re= boxInfoService.saveOrUpdate(boxInfo);
//						//修改之前的托盘状态
//						BoxInfo boxInfoOld = new BoxInfo();
//						boxInfoOld.setBoxCellId(0);
//                        boxInfoOld.setBoxState(BoxInfoState.BOXINFO_STATE_ZERO);
//						boxInfoOld.setHasGoods(BoxInfoState.BOXINFO_GOODS_ZERO);
//						boxInfoOld.setBoxCode(boxCodeNow);
//						int editBoxInfo = boxInfoService.updateBoxInfo(boxInfoOld);
//
//						CellInfo cellInfo=new CellInfo();
//						cellInfo.setState(CellInfoState.STATE_ONT);
//						cellInfo.setCellId(cellId);
//						cellInfo.setItemId(itemId);
//						int editCellInfoReNew =cellInfoService.updateCellInfo(cellInfo);
//						//还原之前的货位，托盘
//						CellInfo cellInfoOld=new CellInfo();
//						cellInfoOld.setState(CellInfoState.STATE_ZERO);
//						cellInfoOld.setCellId(boxCellId);
//						cellInfoOld.setItemId(0);
//						int editCellInfoReOld =cellInfoService.updateCellInfo(cellInfoOld);
//
//						if(re==false||editBoxInfo==0||editCellInfoReNew==0||editCellInfoReOld==0){
//							try {
//								log.error("修改托盘信息出错");
//								throw new Exception("修改货位信息出错，手动抛异常");
//							} catch (Exception e) {
//								e.printStackTrace();
//								TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//							}
//							return ResultGenerator.genFailResult(CommonCode.SERVICE_ERROR, "false");
//						}
//					}else {
//						if(cellInfoByCellCode.getState()!=8) {
//							int editBoxInfoOld =1;
//							int editCellInfoReOld=1;
//							BoxInfo boxInfo = new BoxInfo();
//							boxInfo.setBoxCode(boxCodeEdit);
//							boxInfo.setBoxState(BoxInfoState.BOXINFO_STATE_ONT);
//							boxInfo.setHasGoods(BoxInfoState.BOXINFO_GOODS_ONT);
//							boxInfo.setBoxCellId(cellId);
//							int editBoxInfo = boxInfoService.updateBoxInfo(boxInfo);
//							if(!(boxCodeNow.equals(boxCodeEdit))){
//								BoxInfo boxInfoOld = new BoxInfo();
//								boxInfoOld.setBoxCellId(0);
//								boxInfoOld.setBoxState(BoxInfoState.BOXINFO_STATE_ZERO);
//								boxInfoOld.setHasGoods(BoxInfoState.BOXINFO_GOODS_ZERO);
//								boxInfoOld.setBoxCode(boxCodeNow);
//								editBoxInfoOld = boxInfoService.updateBoxInfo(boxInfoOld);
//							}
//							CellInfo cellInfo=new CellInfo();
//							cellInfo.setState(CellInfoState.STATE_ONT);
//							cellInfo.setCellId(cellId);
//                            cellInfo.setItemId(itemId);
//							int editCellInfoReNew =cellInfoService.updateCellInfo(cellInfo);
//							//还原之前的货位，托盘
//							if(!(cellId.equals(boxCellId))){
//								CellInfo cellInfoOld=new CellInfo();
//								cellInfoOld.setState(CellInfoState.STATE_ZERO);
//								cellInfoOld.setCellId(boxCellId);
//                                cellInfoOld.setItemId(0);
//								editCellInfoReOld =cellInfoService.updateCellInfo(cellInfoOld);
//							}
//							if(editBoxInfo==0||editBoxInfoOld==0||editCellInfoReNew==0||editCellInfoReOld==0){
//								try {
//									log.error("修改托盘信息出错");
//									throw new Exception("修改货位信息出错，手动抛异常");
//								} catch (Exception e) {
//									e.printStackTrace();
//									TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//								}
//								return ResultGenerator.genFailResult(CommonCode.SERVICE_ERROR, "false");
//							}
//						}else {
//							return ResultGenerator.genFailResult(CommonCode.CELLINFO_ERROR, "false");
//						}
//					}
//			}else{
//				CellInfo cellInfo=new CellInfo();
//				cellInfo.setState(CellInfoState.STATE_ONT);
//				cellInfo.setCellId(cellId);
//				cellInfo.setItemId(itemId);
//				cellInfoService.updateCellInfo(cellInfo);
//			}
			 int saveError =  boxItemErrorService.saveBoxItemError(selectBoxItemById);
			 int edit = boxItemService.updateBoxItem(boxItemDto);
			 if(saveError==0||edit==0){
				 try {
					 log.error("修改货位状态出错");
					 throw new Exception("修改货位状态出错，手动抛异常");
				 } catch (Exception e) {
					 e.printStackTrace();
					 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				 }
			 	return ResultGenerator.genFailResult(CommonCode.SERVICE_ERROR, "false");
			 }
			return ResultGenerator.genSuccessResult();
	}

	/**
	 * 删除组盘
	 */
	//@RequiresPermissions("in:boxItem:remove")
	@Log(title = "组盘", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Result remove(String ids){
		String createUserName = ShiroUtils.getLoginName();
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
		//Integer userId = ShiroUtils.getUserId().intValue();
		int pid = sysUser.getPid();
		String[] split = ids.split(",");
		if(split.length>0){
			for (String id : split) {
				BoxItemDto boxItemDto = boxItemService.selectBoxItemById(Integer.parseInt(id));
//				boxItemDto.setCreateUserId(userId);
//				boxItemDto.setPid(pid);
//				boxItemDto.setCreateUserName(createUserName);
				int saveRe = boxItemErrorService.saveBoxItemError(boxItemDto);
				int deRe = boxItemService.deleteBoxItemById(Long.parseLong(id));

				BoxInfoDto boxInfoDto = boxInfoService.getCellIdByBoxCode(boxItemDto.getBoxCode());//通过托盘条码查询现在的货位ID，然后修改当前货位ID的状态，修改为无货状态
				Integer boxCellId = boxInfoDto.getBoxCellId();//当前的货位ID
				CellInfo cellInfo=new CellInfo();
				cellInfo.setState(CellInfoState.STATE_ZERO);
				cellInfo.setCellId(boxCellId);
				cellInfo.setItemId(0);
				int editCellInfoReOld =cellInfoService.updateCellInfo(cellInfo);

				BoxInfo boxInfo = new BoxInfo();
				boxInfo.setBoxCellId(0);
				boxInfo.setBoxState(BoxInfoState.BOXINFO_STATE_ZERO);
				boxInfo.setHasGoods(BoxInfoState.BOXINFO_GOODS_ZERO);
				boxInfo.setBoxCode(boxItemDto.getBoxCode());
				int editBoxInfo = boxInfoService.updateBoxInfo(boxInfo);

				if(saveRe==0||deRe==0||editCellInfoReOld==0||editBoxInfo==0){
					try {
						log.error("删除库存信息出错");
						throw new Exception("删除库存信息出错，手动抛异常");
					} catch (Exception e) {
						e.printStackTrace();
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					}
					return ResultGenerator.genFailResult(CommonCode.SERVICE_ERROR, "false");
				}
			}
			return ResultGenerator.genSuccessResult();
		}
		return ResultGenerator.genFailResult(CommonCode.SERVICE_ERROR, "false");
	}


	/**
	 * 品质异常检验
	 */
//	@RequiresPermissions("in:boxItem:checkOut")
	@Log(title = "检验", businessType = BusinessType.OTHER)
	@PostMapping( "/qualityAbnormalCheck")
	@ResponseBody
	@Transactional
	public Result qualityAbnormalCheck(@RequestBody BoxItemCriteria boxItemCriteria)
	{
		String error = "";
		int count = 0;
		try {
			List<BoxItemDto> boxItemDtos = boxItemService.findList(boxItemCriteria);
			String bool = cellInfoService.judgeBoxItemState(boxItemDtos);
			if (!bool.equals("success")) {
				error = bool;
				throw new RuntimeException();
			}
			for (BoxItemDto boxItemDto : boxItemDtos) {
				cellInfoService.updateCellStateAndBoxStateAndSendTaskInfo(boxItemDto, null, boxItemCriteria.getLoginPersonCardNo());
				count++;
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new ServiceException(CommonCode.GENERAL_WARING_CODE,error);
		}
		return ResultGenerator.genSuccessResult(count);
	}

	//检验入库后
	@PostMapping( "/billInAfterQualityAbnormalCheck")
	@ResponseBody
	@Transactional
	public Result billInAfterQualityAbnormalCheck(@RequestBody BoxItemCriteria boxItemCriteria)
	{
		CellInfoDto cellInfoDto = cellInfoService.getBestCell();
		cellInfoService.updateCellInfoState(cellInfoDto,2);
		BoxInfo boxInfo = boxInfoService.getBoxInfoByBoxCode(boxItemCriteria.getBoxCode());
		boxInfo.setBoxState(2);
		boxInfoService.update(boxInfo);
		BoxItem boxItem = boxItemService.getBoxItemByBoxCode(boxItemCriteria.getBoxCode());
//		TaskInfo taskInfo = new TaskInfo(new GuidUtils().toString(), "105",
////				MyUtils.connectShelfNameAndRowAndColumn(cellInfoDto.getShelfName(),cellInfoDto.getSColumn(),cellInfoDto.getSRow()),
////				TaskTypeConstant.IN_AVAILABLE_BOX,0,boxItem.getQuantity(),boxItem.getBoxCode(), "0",boxItem.getBillInDetailId()
////		);
////		taskInfo.setBarCode(MyUtils.connectPrintString(boxItem.getItemCode(),boxItem.getQuantity(),boxItem.getExp(),boxItem.getBatch(),itemInfoService.findByItemCode(boxItem.getItemCode()).getItemName()));
////		taskInfo.setCardNo(boxItemCriteria.getLoginPersonCardNo());
////		taskInfo.setTaskStartTime(DateUtils.getTime());
////		taskInfoService.save(taskInfo);
		return ResultGenerator.genSuccessResult();
	}

	/**
	 * 库存管理请求账户别名与子库
	 */
	@PostMapping( "/boxItemManage")
	@ResponseBody
	public Result boxItemManage() {
		return ResultGenerator.genSuccessResult();
	}

	@PostMapping("/assignBoxItem")
	@ResponseBody
	public TableDataInfo assignBoxItem(BoxItemDto boxItemDto)
	{
		startPage();
		List<BoxItemDto> list = boxItemService.assignBoxItem(boxItemDto);
		return getDataTable(list);
	}
	/*冻结库存*/
	@PostMapping( "/blockedBoxItem")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public AjaxResult blockedBoxItem(String ids){
		String[] strings = Convert.toStrArray(ids);
		int re = 0;
		for (String id : strings) {
			re = boxItemService.blockedBoxItem(Long.parseLong(id));
		}
		return toAjax(re);
	}
	/*解冻库存*/
	@PostMapping( "/unfreezeBoxItem")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public AjaxResult unfreezeBoxItem(String ids){
		String[] strings = Convert.toStrArray(ids);
		int re = 0;
		for (String id : strings) {
			re = boxItemService.unfreezeBoxItem(Long.parseLong(id));
		}
		return toAjax(re);
	}

	/*原料区库存总览列表*/
	@PostMapping("/selectBoxItem")
	@ResponseBody
	public TableDataInfo selectBoxItem(BoxItemDto boxItemDto) {
		startPage();
		List<BoxItemDto> list = boxItemService.selectBoxItem(boxItemDto);
		return getDataTable(list);
	}
	/*原料区库存报警总览列表*/
	@PostMapping("/selectBoxItemWarning")
	@ResponseBody
	public TableDataInfo selectBoxItemWarning(BoxItemDto boxItemDto) {
		startPage();
		List<BoxItemDto> list = boxItemService.selectBoxItemWarning(boxItemDto);
		return getDataTable(list);
	}
	/*原料区报警库存导出*/
	@PostMapping("/partExcelBoxItemWarning")
	@ResponseBody
	public AjaxResult partExcelBoxItemWarning(BoxItemDto boxItemDto) {
		List<BoxItemDto> list = boxItemService.selectBoxItemWarning(boxItemDto);
		List<BoxItemVo> boxItemVos = new ArrayList();

		list.forEach(e->{
			BoxItemVo boxItemVo = new BoxItemVo();
			boxItemVo.setItemCode(e.getItemCode())
					.setItemName(e.getItemName())
					.setSort(e.getSort())
					.setState(e.getState())
					.setUnit(e.getUnit())
					.setWeight(e.getWeight());
			boxItemVos.add(boxItemVo);
		});
		ExcelUtil<BoxItemVo> util = new ExcelUtil<BoxItemVo>(BoxItemVo.class);
		return util.exportExcel(boxItemVos, "原料区库存总览");
	}

	/*原料区库存明细列表*/
	@PostMapping("/selectBoxItemDetail")
	@ResponseBody
	public TableDataInfo selectBoxItemDetail(BoxItemDto boxItemDto) {
		startPage();
		List<BoxItemDto> list = boxItemService.selectBoxItemDetail(boxItemDto);
		//获取合计重量、合计托数
		BoxItemDto boxItemAll = boxItemService.selectBoxItemAll(boxItemDto);
		for (BoxItemDto itemDto : list) {
			itemDto.setBoxSum(boxItemAll.getBoxSum());
			itemDto.setWeightSum(boxItemAll.getWeightSum());
		}

		return getDataTable(list);
	}
	/*指定出库查物料*/
	@PostMapping("/findBoxItemAll")
	@ResponseBody
	public TableDataInfo findBoxItemAll(BoxItemDto boxItemDto) {
		startPage();
		List<BoxItemDto> list = boxItemService.findBoxItemAll(boxItemDto);
		return getDataTable(list);
	}

	/*线边仓库存明细列表*/
	@PostMapping("/selectBoxItemLine")
	@ResponseBody
	public TableDataInfo selectBoxItemLine(BoxItemDto boxItemDto) {
		startPage();
		List<BoxItemDto> list = boxItemService.selectBoxItemLine(boxItemDto);
		return getDataTable(list);
	}
	/*查询库房所有的批次*/
	@PostMapping("/findBoxItemBatch")
	@ResponseBody
	public List<BoxItemDto> findBoxItemBatch() {
		return boxItemService.findBoxItemBatch();
	}

	/*移库查询库位*/
	//查询排
	@PostMapping("/findPai")
	@ResponseBody
	public List<CellInfo> findPai(CellInfo cellInfo) {
		List<CellInfo> list = boxItemService.findPai(cellInfo);
		return list;
	}
	//查询列
	@PostMapping("/findLie")
	@ResponseBody
	public List<CellInfo> findLie(CellInfo cellInfo) {
		List<CellInfo> list = boxItemService.findLie(cellInfo);
		return list;
	}
	//查询层
	@PostMapping("/findCeng")
	@ResponseBody
	public List<CellInfo> findCeng(CellInfo cellInfo) {
		List<CellInfo> list = boxItemService.findCeng(cellInfo);
		return list;
	}
	//查询库位
	@PostMapping("/findCell")
	@ResponseBody
	public List<CellInfo> findCell(CellInfo cellInfo) {
		List<CellInfo> list = boxItemService.findCell(cellInfo);
		return list;
	}

	/*移库*/
	@PostMapping("/moveCell")
	@ResponseBody
	@Transactional
	public Result moveCell(BoxItemDto boxItemDto){
		String createUserName = ShiroUtils.getLoginName();

		//1.查询目标库位是否闲置,如果闲置则锁定
		CellInfo cell = workTasksService.findCellStateByCode(boxItemDto);
		if(cell.getState() != 0){
			return ResultGenerator.genFailResult(CommonCode.CELLINFO_ERROR);
		}
		//冻结托盘
		boxItemService.blockedBoxItem(boxItemDto.getId());
		//2.查询物料所属堆垛机等信息
		BoxItemDto boxItemOld = workTasksService.findBoxItemById(boxItemDto.getId());
		//判断一层货物不能去二层,二层货物不能去一层
		int oldStr = Integer.parseInt(boxItemOld.getCellCode().substring(boxItemOld.getCellCode().length()-2));
		int newStr = Integer.parseInt(boxItemDto.getCellCode().substring(boxItemOld.getCellCode().length()-2));
		if(oldStr == 1 && newStr !=1){
			return ResultGenerator.genFailResult(CommonCode.MOVEBOX_ERROR);
		} else if (newStr==1 && oldStr !=1) {
			return ResultGenerator.genFailResult(CommonCode.MOVEBOX_ERROR);
		}
		//锁定新货位
		workTasksService.updateCell1(boxItemDto.getCellCode());
		//更改托盘货位
		boxItemDto.setCellId(cell.getCellId());
		boxItemService.updateBoxItemCell(boxItemDto);

		//3.查询目标货位堆垛机是否一样
		RequestWcsRedis requestWcsRedis = new RequestWcsRedis();
		if(!boxItemOld.getShelfId().equals(boxItemDto.getShelfId())){
			//不同堆垛机
			requestWcsRedis.setType(4)//移库
					.setAimlocation(boxItemDto.getCellCode())//目标库位
					.setLocation(boxItemOld.getCellCode());
		}else {
			//相同堆垛机
			requestWcsRedis.setType(3)//移库
					.setAimlocation(boxItemDto.getCellCode())
					.setLocation(boxItemOld.getCellCode());
		}
		//4.下发出库任务redis
		jedisServiceUtil.leftPush("YL:BillOut", requestWcsRedis);
		//5.生成移库记录
		SimpleDateFormat date = new SimpleDateFormat("yyyyMMddHHmmss");
		String YK = "YK"+date.format(new Date());
		FpMoveMaster fpMoveMaster = new FpMoveMaster();
		fpMoveMaster.setOrderNum(YK)//单号
				.setCarrierId(boxItemOld.getBoxCode())//托盘
				.setAreaCode(boxItemOld.getCellCode())//旧库位
				.setMoveAreaCode(boxItemDto.getCellCode())//新库位
				.setCreateUserName(createUserName);//创建人
		fpMoveService.insertMoveMaster(fpMoveMaster);
		return ResultGenerator.genFailResult(CommonCode.WS_SUCCESS);
	}
	/*移库成功,库位信息解锁,托盘解冻*/
	@PostMapping("/moveCellOver")
	@ResponseBody
	@Transactional
	public Result moveCellOver(@RequestBody RequestMove requestMove){
		//旧货位空闲
		workTasksService.updateCellState(requestMove.getAreaCode());
		//根据新货位解冻托盘
		boxItemService.updateBoxItemState(requestMove.getMoveAreaCode());
		return ResultGenerator.genFailResult(CommonCode.WS_SUCCESS);
	}

	/*质量转换*/
	@PostMapping("/updateBillInState")
	@ResponseBody
	@Transactional
	public Result updateBillInState(@RequestBody List<BoxItemDto> boxItemList){
		String createUserName = ShiroUtils.getLoginName();
		//创建质检单
		SimpleDateFormat date = new SimpleDateFormat("yyyyMMdd-HHmmss");
		String zJCode = "ZJ"+date.format(new Date());

		BoxItemState boxItemState = new BoxItemState();
		boxItemState.setCreateName(createUserName)
				.setState(1)
				.setStateNo(zJCode);
		boxItemService.insertBoxItemState(boxItemState);

		BoxItemStateDetail boxItemStateDetail = new BoxItemStateDetail();
		boxItemList.forEach(boxItem->{
			BoxItemDto boxItemMSG = boxItemService.findBoxItemMSG(boxItem.getId());
			//创建质检明细
			boxItemStateDetail.setStateId(boxItemState.getStateId())
					.setOldBillInState(boxItemMSG.getBillInState())
					.setBillInState(boxItem.getBillInState())
					.setItemId(boxItemMSG.getItemId());
			boxItemService.insertBoxItemStateDetail(boxItemStateDetail);
			//更改质量
			boxItemService.updateBillInState(boxItem);
		});

		return ResultGenerator.genFailResult(CommonCode.WS_SUCCESS);
	}
	/*批次转换*/
	@PostMapping("/updateBatch")
	@ResponseBody
	@Transactional
	public Result updateBatch(@RequestBody List<BoxItemDto> boxItemList){
		String createUserName = ShiroUtils.getLoginName();
		SimpleDateFormat date = new SimpleDateFormat("yyyyMMdd-HHmmss");
		String pCCode = "PC"+date.format(new Date());

		BoxItemBatch boxItemBatch = new BoxItemBatch();
		boxItemBatch.setCreateName(createUserName)
				.setState(1)
				.setBatchNo(pCCode);
		boxItemService.insertBoxItemBatch(boxItemBatch);

		BoxItemBatchDetail boxItemBatchDetail = new BoxItemBatchDetail();
		boxItemList.forEach(boxItem->{
			BoxItemDto boxItemMSG = boxItemService.findBoxItemMSG(boxItem.getId());
			//创建质检明细
			boxItemBatchDetail.setBatchId(boxItemBatch.getBatchId());
			boxItemBatchDetail.setOldBatch(boxItemMSG.getBatch());
			boxItemBatchDetail.setBatch(boxItem.getBatch());
			boxItemBatchDetail.setItemId(boxItemMSG.getItemId());
			boxItemService.insertBoxItemBatchDetail(boxItemBatchDetail);
			//更改批次
			boxItemService.updateBatch(boxItem);
		});

		return ResultGenerator.genFailResult(CommonCode.WS_SUCCESS);
	}

	/*导出库存*/
	//@RequiresPermissions("in:boxItem:exportBufferStorage")
	@PostMapping("/partExcelRevolutionStorage")
	@ResponseBody
	public AjaxResult partExcelRevolutionStorage(BoxItemDto boxItemDto) {
		List<BoxItemDto> list = boxItemService.selectBoxItem(boxItemDto);
		List<BoxItemVo> boxItemVos = new ArrayList();

		list.forEach(e->{
			BoxItemVo boxItemVo = new BoxItemVo();
			boxItemVo.setItemCode(e.getItemCode())
					.setItemName(e.getItemName())
					.setSort(e.getSort())
					.setState(e.getState())
					.setUnit(e.getUnit())
					.setWeight(e.getWeight());
			boxItemVos.add(boxItemVo);
		});

		ExcelUtil<BoxItemVo> util = new ExcelUtil<BoxItemVo>(BoxItemVo.class);
		return util.exportExcel(boxItemVos, "原料区库存总览");
	}

	/*特殊出库按钮*/
	@PostMapping("/spOutBoxItem")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Result spOutBoxItem(@RequestBody List<BoxItemDto> boxItemList){
		String userName = ShiroUtils.getLoginName();
		Integer userId = ShiroUtils.getUserId();

		//1.创建SAP特殊出库计划
		BillOutSapDto billOutSap = new BillOutSapDto();//sap
		billOutSap.setCreateName(userName)
				.setCreateId(userId)
				.setType(5)//特殊出库
				.setSapNo(boxItemList.get(0).getSapNo())
				.setBillState(2).setState(1);
		billOutSapService.insertBillOutSap(billOutSap);
        //2.创建特殊出库计划
        Long outNumber = workTasksService.getBillOutNumber();
        String billNo = "JH" + outNumber;
        BillOutMaster billOutMaster = new BillOutMaster();
        billOutMaster.setState(3)//3出库完成
                .setSapState(1) //过账
                .setBillNo(billNo)
                .setOutNumber(outNumber)
                .setType(billOutSap.getType())
                .setSapNo(billOutSap.getSapNo())
                .setSapId(billOutSap.getBillOutSapId())
                .setCreateUserName(userName)
                .setAuditUserId(userId)
                .setAuditUserName(userName);
        billOutSapService.insertBillOutMaster(billOutMaster);
		//3.创建出库单
		Long planNumber = workTasksService.getPlanNumber();
		String plamNo = "CK" + planNumber;
		BillOutPlan billOutPlan = new BillOutPlan();
		billOutPlan.setCreateName(userName)
				.setPlanNo(plamNo) //出库单号
				.setPlanNumber(planNumber)//流水号
				.setState(3)//已完成
				.setSapNo(boxItemList.get(0).getSapNo()) //出库工单号
				.setBillId(billOutMaster.getBillId()); //出库计划单id
		billOutMasterService.insertBillOutPlan(billOutPlan);

		for (BoxItemDto boxItem : boxItemList) {
			//4.托盘状态出库中
			boxItemService.outBoxItem(boxItem.getId());
            //5.创建SAP特殊出库计划明细
			boxItem = boxItemService.findByItemId(boxItem.getId());
			boxItem.setBillOutSapId(billOutSap.getBillOutSapId());
			billOutSapService.insertDetailByBoxItem(boxItem);
			//6.创建出库单明细
			BillOutDetail billOutDetail = new BillOutDetail();
			billOutDetail.setPlanId(billOutPlan.getBillOutPlanId())//计划id
					.setWeight(boxItem.getWeight())
                    .setItemId(boxItem.getItemId())
                    .setDeviceName("特殊出库")
					.setState(2);

			billOutMasterService.insertBillOutDetail(billOutDetail);

			//7.创建出库流水
			BillOutDetailDevice detailDevice = new BillOutDetailDevice();//流水
			detailDevice.setBoxId(boxItem.getId().intValue()) //托id
					.setPlanNo(plamNo)
					.setPlanId(billOutPlan.getBillOutPlanId())
					.setDeviceName("特殊出库")
					.setMemo(boxItem.getMemo())
					.setCreateName(userName)
					.setBillInDetailId(boxItem.getBillInDetailId());//明细id
			billOutMasterService.insertBillOutDetailDevice(detailDevice);
			//8.出库作业
			TaskInfoDto taskInfoDto = new TaskInfoDto();//作业
			taskInfoDto.setId(boxItem.getTaskId())
					.setOutType(5)//出库类型
					.setCreateUserName(userName)//创建人
					.setCurrentDevice("特殊出库")//机台名称
					.setStartPosition("立体库")
					.setEndPosition("立体库");
			workTasksService.updateWorkTasksById(taskInfoDto);
			//9.redis
			RequestWcsRedis requestWcsRedis = new RequestWcsRedis();//redis
			requestWcsRedis.setLocation(boxItem.getCellCode())//库位
					.setType(1)
					.setAimlocation(" ");//任务类型
			jedisServiceUtil.leftPush("YL:BillOut", requestWcsRedis);

		}

		return ResultGenerator.genFailResult(CommonCode.WS_SUCCESS);
	}

	/*指定出库~~~~~~~~~~~~~~~`)*/
	@PostMapping("/fastAllocationTask")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Result fastAllocationTask(@RequestBody InserData inserData){
		String createUserName = ShiroUtils.getLoginName();
		BillOutDetailDevice detailDevice = new BillOutDetailDevice();
		TaskInfoDto taskInfoDto = new TaskInfoDto();
		RequestWcsRedis requestWcsRedis = new RequestWcsRedis();
		//1.新建出库单关联SAP出库单
		BillOutPlan billOutPlan = new BillOutPlan();
		Long planNumber = workTasksService.getPlanNumber();
		String plamNo = "CK" + planNumber;
		billOutPlan.setCreateName(createUserName)
				.setPlanNo(plamNo) //计划单号
				.setPlanNumber(planNumber)//流水号
				.setSapNo(inserData.getBillOutMaster().getSapNo()) //出库计划号
				.setState(1)//待出库
				.setBillId(inserData.getBillOutMaster().getBillId()); //出库计划id
		billOutMasterService.insertBillOutPlan(billOutPlan);

		//获取出库信息,操作每一托的信息
		List<WorkTasks> workTaskList = inserData.getWorkTaskList();
		Float weightSUM = 0f; //总重量
		for (WorkTasks workTasks : workTaskList) {
			weightSUM = weightSUM + workTasks.getWeight();
			//2.锁定托盘
			//iBoxItemService.outBoxItem(Long.valueOf(workTasks.getBoxId()));
			//3.新建出库流水
			detailDevice.setBoxId(workTasks.getBoxId()) //托id
					.setPlanNo(plamNo)
					.setPlanId(billOutPlan.getBillOutPlanId())
					.setDeviceName(workTasks.getDeviceName())
					.setMemo(workTasks.getMemo())
					.setCreateName(createUserName)
					.setBillInDetailId(workTasks.getBillInDetailId());//明细id
			billOutMasterService.insertBillOutDetailDevice(detailDevice);
			//4.入库作业改为出库作业
			taskInfoDto.setId(workTasks.getTaskId()) //入库作业id
					.setOutType(workTasks.getOutType())//出库类型
					.setCreateUserName(createUserName)//创建人
					.setCurrentDevice(workTasks.getDeviceName())//机台名称
					.setStartPosition("立体库")
					.setEndPosition("立体库");
			workTasksService.updateWorkTasksById(taskInfoDto);
			//5.放入redis
			requestWcsRedis.setLocation(workTasks.getCellCode())//库位
					.setType(1)
					.setAimlocation(" ");//任务类型
			jedisServiceUtil.leftPush("YL:BillOut", requestWcsRedis);
		}
		//5.创建出库单明细
		//5.1准备数据
		BillOutDetail billOutDetail = new BillOutDetail();
		billOutDetail.setPlanId(billOutPlan.getBillOutPlanId())//入库单id
				.setWeight(weightSUM)//合计重量
				.setItemId(workTaskList.get(0).getItemId())
				.setDeviceId(workTaskList.get(0).getDeviceid())
				.setDeviceName(workTaskList.get(0).getDeviceName());

		//5.2保存
		billOutMasterService.insertBillOutDetail(billOutDetail);
		//6.SAP出库明细出库数量变动


		return ResultGenerator.genFailResult(CommonCode.WS_SUCCESS);
	}
	//   /in/boxItem/findBoxItemAll

}
